package com.wdh.testq.tools;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;

import com.wdh.testq.dialog.PermissionDialog;
import com.werb.pickphotoview.util.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by:zheng zhong on 2016/8/6 16:16
 * Email zheng_zhong@163.com
 */
public class PhotoUtils {
    private static final String TAG = "PhotoUtils";
    private static Uri uri;
    private static File tempFile;
    private static File cropFile;
    private static Uri cropUri;

    /**
     * @param activity    当前activity
     * @param requestCode 调用系统相机请求码
     */
    public static void takePicture(final Activity activity, final int requestCode) {
        PermissionTools.getInstance()
                .bind(activity)
                .permission(PermissionTools.CHECK_CAMERA)
                .call(new CallBack() {
                    @Override
                    protected void onAction(List<Resultful> data) {
                        if (data == null || data.get(0).isAllow()) {
                            jumpCamera(activity, requestCode);
                        } else {
                            PermissionDialog dialog = new PermissionDialog(activity).Build();
                            dialog.setPermissionList(PermissionDialog.PermissionType.CAMERA)
                                    .show();
                        }
                    }
                }).excute();
    }

    /**
     * new File(Environment.getExternalStorageDirectory().getPath(), FileUtils.getCropPhotoFileName());
     * 我用的是Environment.getExternalStorageDirectory()来获取文件路径的，这个方法在api 29是过时的因此我用了
     * cropFile = new File(activity.getExternalCacheDir(), FileUtils.getCropPhotoFileName());
     * 来设置文件路径发现可以正常裁剪
     *
     * @param activity
     * @param requestCode
     */
    private static void jumpCamera(Activity activity, int requestCode) {
        tempFile = new File(activity.getExternalCacheDir(), FileUtils.getPhotoFileName());
        cropFile = new File(activity.getExternalCacheDir(), FileUtils.getCropPhotoFileName());
        //调用系统相机
        Intent intentCamera = new Intent();
        uri = Uri.fromFile(tempFile);
        cropUri = Uri.fromFile(cropFile);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                String status = Environment.getExternalStorageState();
                // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
                if (status.equals(Environment.MEDIA_MOUNTED)) {
                    uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
                } else {
                    uri = activity.getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
                }
            } else {
                intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", tempFile);//通过FileProvider创建一个content类型的Uri
            }
        }
        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //将拍照结果保存至photo_file的Uri中，不保留在相册中
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        activity.startActivityForResult(intentCamera, requestCode);
    }

    public static void openPic(final Activity activity, final int requestCode) {
        openPic(activity, requestCode, true);
    }

    /**
     * @param activity    当前activity
     * @param requestCode 打开相册的请求码
     */
    public static void openPic(final Activity activity, final int requestCode, final boolean crop) {
        PermissionTools.getInstance()
                .bind(activity)
                .permission(PermissionTools.READ_EXTERNAL_STORAGE)
                .call(new CallBack() {
                    @Override
                    protected void onAction(List<Resultful> data) {
                        if (data == null || data.get(0).isAllow()) {
                            if (crop)
                                jumpAlbum(activity, requestCode);
                            else
                                jumpAlbumNoCrop(activity, requestCode);
                        } else {
                            PermissionDialog dialog = new PermissionDialog(activity).Build();
                            dialog.setPermissionList(PermissionDialog.PermissionType.READ_EXTERNAL_STORAGE)
                                    .show();
                        }
                    }
                }).excute();
    }

    private static void jumpAlbum(Activity activity, int requestCode) {
        tempFile = new File(activity.getExternalCacheDir(), FileUtils.getPhotoFileName());
        cropFile = new File(activity.getExternalCacheDir(), FileUtils.getCropPhotoFileName());
        uri = Uri.fromFile(tempFile);
        cropUri = Uri.fromFile(cropFile);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                String status = Environment.getExternalStorageState();
                // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
                if (status.equals(Environment.MEDIA_MOUNTED)) {
                    uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
                } else {
                    uri = activity.getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
                }
            }
        } else {
            uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", tempFile);
        }
        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        photoPickerIntent.addCategory(Intent.CATEGORY_OPENABLE);//可打开的uri
        photoPickerIntent.setType("image/*");
        photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        activity.startActivityForResult(photoPickerIntent, requestCode);
    }

    private static void jumpAlbumNoCrop(Activity activity, int requestCode) {
        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        photoPickerIntent.setType("image/*");
        activity.startActivityForResult(photoPickerIntent, requestCode);
    }

    /**
     * @param activity    当前activity
     * @param requestCode 剪裁图片的请求码
     */
    public static void cropImageUri(Activity activity, int width, int height, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", height);
        intent.putExtra("outputX", 500 * width / height);
        intent.putExtra("outputY", 500);
//        intent.putExtra("scale", true);
        //将剪切的图片保存到目标Uri中
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * @param activity    当前activity
     * @param requestCode 剪裁图片的请求码
     */
    public static void cropImageUri(Activity activity, int width, int height, Uri u, int requestCode) {
        cropImageUri(activity, 500, width, height, u, requestCode);
    }

    public static void cropImageUri(Activity activity, int defalut, int width, int height, Uri u, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(u, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", height);
        intent.putExtra("outputX", defalut * width / height);
        intent.putExtra("outputY", defalut);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
//        intent.putExtra("scale", true);
        //将剪切的图片保存到目标Uri中
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 读取uri所在的图片
     *
     * @param uri      图片对应的Uri
     * @param mContext 上下文对象
     * @return 获取图像的Bitmap
     */
    public static Bitmap getBitmapFromUri(Uri uri, Context mContext) {
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), uri);
            bitmap = rotaingImageView(readPictureDegree(mContext, uri.getPath()), bitmap);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @path 7.0适配自己定义的file_path文件里path值
     * file-path	物理路径为Context.getFilesDir() + /@path/*
     * cache-path	物理路径为Context.getCacheDir() + /@path/*
     * external-path	物理路径为Environment.getExternalStorageDirectory() + /@path/*
     * external-files-path	物理路径为Context.getExternalFilesDir(String) + /@path/*
     * external-cache-path	物理路径为Context.getExternalCacheDir() + /@path/*
     */
    public static int readPictureDegree(Context context, String path) {
        int degree = 0;
        path = path.replace("pick_camera", context.getExternalCacheDir() + "/DCIM");
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /*
     * 旋转图片
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    public static Bitmap getCropBitmap(Context mContext) {
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), cropUri);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getCropPath() {
        try {
            return cropUri.getPath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap getTakePhotoBitmap(Context mContext) {
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(tempFile.getPath());
            bitmap = rotaingImageView(readPictureDegree(mContext, tempFile.getPath()), bitmap);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getTempFilePath() {
        return tempFile == null ? "" : tempFile.getPath();
    }

    /**
     * @param context 上下文对象
     * @param uri     当前相册照片的Uri
     * @return 解析后的Uri对应的String
     */
    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        String pathHead = "file:///";
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return pathHead + context.getExternalCacheDir() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);

                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), NumUtil.ofLong(id));

                return pathHead + getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return pathHead + getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return pathHead + getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return pathHead + uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


}
